package com.aind.user.controller;

import com.aind.common.constant.SessionContant;
import com.aind.common.utils.verify.VerifyCodeUtil;
import com.aind.user.model.User;
import com.aind.user.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * Created by lpeng on 2017/2/22.
 */
@Controller
@RequestMapping(value = "/loginAndRegister")
public class LoginAndRegistController {
    private static Logger logger = Logger.getLogger(LoginAndRegistController.class);
    @Autowired
    private UserService userService;

    @RequestMapping(value = "/regist", method = RequestMethod.POST)
    public ModelAndView regist(@RequestParam(value = "account", required = true) String account,
                               @RequestParam(value = "password", required = true) String password,
                               @RequestParam(value = "email", required = true) String email,
                               @RequestParam(value = "verifyCode", required = true) String verifyCode,
                               HttpSession session) {
        ModelAndView mav = new ModelAndView("/jsps/msg");
        mav.addObject("code", "error");
        String verifyCode1 = (String) session.getAttribute("vCode");
        if (StringUtils.isNotEmpty(verifyCode1) && verifyCode1.equalsIgnoreCase(verifyCode)) {
            User user = new User();
            user.setAccount(account);
            user.setPassword(password);
            user.setEmail(email);
            userService.save(user);
            mav.addObject("code", "success");
        }
        return mav;
    }

    /**
     * 登录
     *
     * @param account    帐号
     * @param password   密码
     * @param verifyCode 验证码
     * @param session    session
     * @param response   响应
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = "/login")
    public ModelAndView login(@RequestParam(value = "account", required = true) String account,
                              @RequestParam(value = "password", required = true) String password,
                              @RequestParam(value = "verifyCode", required = true) String verifyCode,
                              HttpSession session, HttpServletResponse response) throws UnsupportedEncodingException {
        ModelAndView mav = new ModelAndView("/jsps/user/login");
        User user = new User();
        user.setAccount(account);
        user.setPassword(password);
        String vCode = (String) session.getAttribute("vCode");
        if (StringUtils.isEmpty(verifyCode) || StringUtils.isEmpty(vCode) || !vCode.equalsIgnoreCase(verifyCode)) {
            mav.addObject("msg", "验证码错误");
            mav.addObject("user", user);
            return mav;
        }
        user = userService.getUserByAccountAndPswd(account, password);
        if (null == user) {
            mav.addObject("msg", "帐号或密码错误");
            mav.addObject("user", user);
            return mav;
        }
        if (user.getStatus() != 1) {
            mav.addObject("msg", "未激活");
            mav.addObject("user", user);
            return mav;
        }
        mav.setViewName("/index");
        session.setAttribute(SessionContant.SESSION_USER, user);
        Cookie cookie = new Cookie("account", URLEncoder.encode(account, "UTF-8"));
        cookie.setMaxAge(60 * 60 * 24 * 7);//cookie七天内有效
        cookie.setPath("/");
        response.addCookie(cookie);
        return mav;
    }

    /**
     * 激活用户
     *
     * @param activationCode 激活码
     * @param userId         user_id
     * @return
     */
    @RequestMapping(value = "/activateUser")
    public ModelAndView activateUser(@RequestParam(value = "activationCode", required = true) String activationCode,
                                     @RequestParam(value = "userId", required = true) Long userId) {
        ModelAndView mav = new ModelAndView("/jsps/msg");
        mav.addObject("code", "error");
        if (StringUtils.isNotEmpty(activationCode) && null != userId) {
            boolean flag = userService.activateUser(userId, activationCode);
            if (flag) {
                mav.addObject("code", "success");
            }
        }
        return mav;
    }

    /**
     * 校验用户名
     *
     * @param account 帐号
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/checkAccount", produces = "text/json;charset=UTF-8")
    public String checkAccount(@RequestParam(value = "param", required = true) String account) {
        String ret = "{\"info\":\"用户名已存在\",\"status\":\"n\"}";
        if (StringUtils.isNotEmpty(account)) {
            boolean flag = userService.checkAccount(account);
            if (flag) {
                ret = "{\"info\":\"验证通过\",\"status\":\"y\"}";
            }
        }
        return ret;
    }

    /**
     * 验证验证码是否正确
     *
     * @param param   验证码
     * @param session session
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/validateVerifyCode", produces = "text/json;charset=UTF-8")
    public String validateVerifyCode(@RequestParam(required = true) String param, HttpSession session) {
        String ret = "{\"info\":\"验证码错误\",\"status\":\"n\"}";
        String verifyCode = (String) session.getAttribute("vCode");
        if (StringUtils.isNotEmpty(verifyCode)) {
            if (verifyCode.equalsIgnoreCase(param)) {
                session.removeAttribute("vCode");
                ret = "{\"info\":\"验证通过\",\"status\":\"y\"}";
            }
        }
        return ret;
    }

    /**
     * 获取图片验证码
     *
     * @param response
     * @param session
     * @throws Exception
     */
    @RequestMapping("/getVerifyCode")
    public void getVerifyCode(HttpServletResponse response, HttpSession session) throws Exception {
        VerifyCodeUtil.outVerifyCode(response, session);
    }
}
